const app = getApp();
Page({
  data: {
    id: '',
    editable: false,
    gpxInfo: {},
    polyline: [],
    longitude: 116.397428,
    latitude: 39.90923,    includePoints: [],
    markers: [],
    images: [],
    imageGroups: [], // 新增：用于分组图片
    defaultDate: '',
  },
  onLoad(options) {
    console.log('onLoad options:', options);
    const id = options.id || '';
    // 修正：如果没有edit参数，默认editable为true
    let editable = true;
    if (options.hasOwnProperty('edit')) {
      editable = options.edit === '1';
    }
    this.setData({ id, editable });
    const now = new Date();
    const pad = n => n < 10 ? '0' + n : n;
    const today = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
    this.setData({ defaultDate: today });
    if (id) {
      wx.request({
        url: `${app.globalData.baseUrl}/api/gpx/info/${id}`,
        method: 'GET',
        success: res => {
          if (res.data && res.data.code === 200 && res.data.data) {
            const info = res.data.data;
            // 处理startTime格式为'YYYY-MM-DDTHH:mm'，picker才能正确显示
            let startTime = info.startTime;
            if (!startTime) {
              const now = new Date();
              const pad = n => n < 10 ? '0' + n : n;
              startTime = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}`;
            } else if (startTime.length === 16 && startTime[10] === ' ') {
              // 'YYYY-MM-DD HH:mm' => 'YYYY-MM-DDTHH:mm'
              startTime = startTime.replace(' ', 'T');
            }
            this.setData({
              gpxInfo: { ...info, startTime },
            });
            // 拉取gpx文件内容并解析
            wx.request({
              url: `${app.globalData.baseUrl}/api/gpx/download/${encodeURIComponent(info.filename)}`,
              method: 'GET',
              responseType: 'text',
              success: gpxRes => {
                const gpxStr = gpxRes.data;
                const points = this.parseGpxPoints(gpxStr);
                const roadName = this.parseGpxRoadName(gpxStr);
                const now = new Date();
                const pad = n => n < 10 ? '0' + n : n;
                const startTime = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
                this.setData({
                  polyline: points.length ? [{ points, color: '#FF0000DD', width: 4 }] : [],
                  longitude: points.length ? points[0].longitude : 116.397428,
                  latitude: points.length ? points[0].latitude : 39.90923,
                  includePoints: points,
                  markers: points.length ? [
                    { id: 0, latitude: points[0].latitude, longitude: points[0].longitude, title: '起点', width: 28, height: 28, color: '#07c160', callout: { content: '起点', color: '#fff', bgColor: '#07c160', padding: 4, borderRadius: 8, display: 'ALWAYS' } },
                    { id: 1, latitude: points[points.length-1].latitude, longitude: points[points.length-1].longitude, title: '终点', width: 28, height: 28, color: '#FFD600', callout: { content: '终点', color: '#fff', bgColor: '#FFD600', padding: 4, borderRadius: 8, display: 'ALWAYS' } }
                  ] : [],
                  'gpxInfo.roadName': roadName || info.roadName || '',
                  'gpxInfo.startTime': info.startTime || startTime
                });
                this.loadImages();
              }
            });
          }
        }
      });
    }
  },
  onReady() {
    this.mapCtx = wx.createMapContext('map', this);
  },
  tapLegendStart() {
    if (this.data.markers && this.data.markers.length > 0 && this.mapCtx) {
      const marker = this.data.markers[0];
      this.mapCtx.moveToLocation({
        longitude: marker.longitude,
        latitude: marker.latitude
      });
    }
  },
  tapLegendEnd() {
    if (this.data.markers && this.data.markers.length > 1 && this.mapCtx) {
      const marker = this.data.markers[1];
      this.mapCtx.moveToLocation({
        longitude: marker.longitude,
        latitude: marker.latitude
      });
    }
  },
  tapLegendCurrent() {
    // 获取当前位置并平移地图
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        // 可选：添加当前位置marker
        const userMarker = {
          id: 99,
          latitude: res.latitude,
          longitude: res.longitude,
          iconPath: '/images/default.jpg', // 可自定义
          width: 32,
          height: 32,
          title: '我',
          callout: {
            content: '我',
            color: '#fff',
            bgColor: '#007aff',
            padding: 4,
            borderRadius: 8,
            display: 'ALWAYS'
          }
        };
        let markers = this.data.markers.filter(m => m.id !== 99);
        markers.push(userMarker);
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude,
          markers
        });
        if (this.mapCtx) {
          this.mapCtx.moveToLocation({
            longitude: res.longitude,
            latitude: res.latitude
          });
        }
      },
      fail: () => {
        wx.showToast({ title: '定位失败', icon: 'none' });
      }
    });
  },
  parseGpxPoints(gpxStr) {
    const pointReg = /<trkpt[\s\S]*?lat="([\d\.]+)"[\s\S]*?lon="([\d\.]+)"[\s\S]*?>[\s\S]*?<\/trkpt>/g;
    const points = [];
    let match;
    while ((match = pointReg.exec(gpxStr))) {
      points.push({ latitude: parseFloat(match[1]), longitude: parseFloat(match[2]) });
    }
    return points;
  },
  parseGpxRoadName(gpxStr) {
    const match = gpxStr.match(/<name>([^<]+)<\/name>/);
    return match ? match[1] : '';
  },
  onInputInfo(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`gpxInfo.${field}`]: e.detail.value });
  },
  onPickStartTime(e) {
    this.setData({ 'gpxInfo.startTime': e.detail.value });
  },
  onPickDate(e) {
    this.setData({ 'gpxInfo.date': e.detail.value });
  },
  onPickTime(e) {
    this.setData({ 'gpxInfo.time': e.detail.value });
  },
  getFullStartTime() {
    const { date, time } = this.data.gpxInfo;
    return date && time ? `${date} ${time}` : '';
  },
  // 加载图片列表
  loadImages() {
    if (!this.data.gpxInfo.id) return;
    wx.request({
      url: `${app.globalData.baseUrl}/api/gpx/image/list/${this.data.gpxInfo.id}`,
      method: 'GET',
      success: res => {
        if (res.data && res.data.code === 200) {
          let images = res.data.data.map((img, idx) => ({
            ...img,
            url: img.filename ? `${app.globalData.baseUrl}/uploads/img/${img.filename}` : '',
            globalIndex: idx
          }));
          // 过滤掉默认图片
          if (images.length === 1 && images[0].url.endsWith('/uploads/img/1.jpg')) {
            images = [];
          }
          // 分组，每组2张
          const imageGroups = [];
          for (let i = 0; i < images.length; i += 2) {
            imageGroups.push([
              images[i],
              images[i + 1] ? images[i + 1] : null
            ].filter(Boolean));
          }
          // 编辑模式下，布局加号
          if (this.data.editable) {
            if (images.length === 0) {
              // 没有图片时，只显示一个加号明信片（不设置 imageGroups）
              this.setData({ images: [], imageGroups: [] });
              return;
            }
            if (images.length % 2 === 0) {
              // 偶数，新开一页
              imageGroups.push([]);
            }
            // 奇数时，不新开一页，加号在最后一组下方明信片
            this.setData({ images, imageGroups });
            return;
          }
          this.setData({ images, imageGroups });
        }
      }
    });
  },
  // 选择图片并上传
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length,
      success: res => {
        res.tempFilePaths.forEach(path => {
          wx.uploadFile({
            url: `${app.globalData.baseUrl}/api/gpx/image/upload`,
            filePath: path,
            name: 'file',
            formData: { gpxId: this.data.gpxInfo.id },
            success: uploadRes => {
              // 上传成功后刷新图片列表
              this.loadImages();
            },
            fail: err => { console.error('上传失败', err, this.data.gpxInfo.id); }
          });
        });
      }
    });
  },
  // 删除图片
  deleteImage(e) {
    const idx = e.currentTarget.dataset.index;
    const img = this.data.images[idx];
    wx.showModal({
      title: '确认删除？',
      success: res => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/gpx/image/${img.id}`,
            method: 'DELETE',
            success: () => {
              this.loadImages();
            }
          });
        }
      }
    });
  },
  // 编辑图片描述（新版：传图片实体对象）
  editImage(e) {
    const idx = e.currentTarget.dataset.index;
    const img = this.data.images[idx];
    wx.showModal({
      title: '编辑描述',
      editable: true,
      placeholderText: '请输入描述',
      success: res => {
        if (res.confirm && res.content) {
          wx.request({
            url: `${app.globalData.baseUrl}/api/gpx/image/update`,
            method: 'PUT',
            data: { ...img, remark: res.content },
            header: { 'content-type': 'application/json' },
            success: () => {
              this.loadImages();
            }
          });
        }
      }
    });
  },
  // 图片加载成功
  imageLoadReady(e) {
    const idx = e.currentTarget.dataset.index;
    const images = this.data.images;
    if (images[idx]) {
      images[idx].loadReady = true;
      this.setData({ images });
    }
  },
  // 图片加载失败
  imageLoadError(e) {
    const idx = e.currentTarget.dataset.index;
    const images = this.data.images;
    if (images[idx]) {
      images[idx].url = '/images/default.jpg';
      images[idx].loadReady = false;
      this.setData({ images });
    }
  },
  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const urls = this.data.images.map(img => img.url);
    wx.previewImage({
      current: urls[index],
      urls
    });
  },
  // 保存gpx信息和图片信息
  confirmInfo() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/gpx/info`,
      method: 'PUT',
      data: {
        ...this.data.gpxInfo,
        images: this.data.images.map(img => ({ filename: img.filename, remark: img.remark })),
        startTime: this.getFullStartTime()
      },
      header: { 'content-type': 'application/json' },
      success: res => {
        wx.showToast({ title: '已保存', icon: 'success' });
        if (this.options && this.options.from === 'schedule') {
          wx.navigateBack();
        } else {
          wx.redirectTo({ url: '/pages/routes/routes' });
        }
      }
    });
  },
  cancelInfo() {
    wx.navigateBack({ delta: 1 });
  },
  onNavBtnTap() {
    // 终点导航
    const { endLat, endLng, roadName } = this.data.gpxInfo;
    if (endLat && endLng) {
      wx.openLocation({
        latitude: Number(endLat),
        longitude: Number(endLng),
        name: roadName || '终点',
        scale: 16
      });
    } else {
      wx.showToast({ title: '无终点信息', icon: 'none' });
    }
  },
  onNavStart() {
    const { startLat, startLng, roadName } = this.data.gpxInfo;
    if (startLat && startLng) {
      wx.openLocation({
        latitude: Number(startLat),
        longitude: Number(startLng),
        name: (roadName ? roadName + '-起点' : '起点'),
        scale: 16
      });
    } else {
      wx.showToast({ title: '无起点信息', icon: 'none' });
    }
  },
  onNavEnd() {
    const { endLat, endLng, roadName } = this.data.gpxInfo;
    if (endLat && endLng) {
      wx.openLocation({
        latitude: Number(endLat),
        longitude: Number(endLng),
        name: (roadName ? roadName + '-终点' : '终点'),
        scale: 16
      });
    } else {
      wx.showToast({ title: '无终点信息', icon: 'none' });
    }
  }
});
